package org.kkhweb.checkbook;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

public class PreferencesActivity extends PreferenceActivity {

	private Intent signinIntent;
	
	private SharedPreferences settings;
	private Editor editor;
	private SimpleHTTPClient httpClient;
	private ProgressDialog dialog;
	private Preference signoutPref;
	private Preference signinPref;

    public static final String PREFS_NAME = "MyCheckbookSettings";
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.restore_settings();	
        
        addPreferencesFromResource(R.xml.preferences);
        this.signoutPref = (Preference) findPreference("signout");
        this.signinPref = (Preference) findPreference("signin");
        
        this.signinIntent = new Intent(this, SignInActivity.class);
        
        this.setPrefs(this.settings.getBoolean("logged_in", false));
    }
	@Override
    protected void onStart() {
        super.onStart();
        this.restore_settings();
        this.setPrefs(this.settings.getBoolean("logged_in", false));
        // The activity is about to become visible.
    }
    @Override
    protected void onResume() {
        super.onResume();
        this.restore_settings();
        this.setPrefs(this.settings.getBoolean("logged_in", false));        
        // The activity has become visible (it is now "resumed").
    }
    @Override
    protected void onPause() {
        super.onPause();
        this.restore_settings();
        this.setPrefs(this.settings.getBoolean("logged_in", false));
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
    	super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
    
    
    public void setPrefs(boolean loggedIn)
    {
        if(loggedIn == true) { //User is logged in
	        signinPref.setTitle("Signed In");
	        signinPref.setSummary("Username: "+settings.getString("user_name", "null"));
	        signinPref.setEnabled(false);

	        signoutPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
	            public boolean onPreferenceClick(Preference preference) {
	            	signOutThread();
	                return true;
	            }
	        });
        	signoutPref.setEnabled(true);
        } else { //User is not logged in
        	signinPref.setTitle("Please Signin");
	        signinPref.setSummary("Touch here to enter your account info");
	        signinPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
	            public boolean onPreferenceClick(Preference preference) {
	            	startActivity(signinIntent);
	                return true;
	            }
	        });            
	        signinPref.setEnabled(true);
	        
        	signoutPref.setEnabled(false);
        }    	
    }

  //SignIn Thread    
  	protected void signOutThread()
  	{
  		httpClient = new SimpleHTTPClient();
  		
      	dialog = ProgressDialog.show(PreferencesActivity.this, "Logging Out", 
                  "Please wait...", false);  		    

  	    new Thread() {
  		    @Override
  		    public void run()
  		    {         
  		    	httpClient.setURL(Globals.buildURL("signout"));
  		    	httpClient.sendRequest();
  		        
  		        handler.sendEmptyMessage(0);
  		    }
  	    }.start();
  	}

  //Handler for SignOutThread    
  	private Handler handler = new Handler() {
  		@Override
  		public void handleMessage(Message msg) {
  			super.handleMessage(msg);
  			dialog.dismiss();
      		
      		if(httpClient.hasError()) {
      			toast(httpClient.getError());
      		} else {
        		editor.putInt("user_id", 0);
        		editor.putString("user_name", "null");
        		editor.putBoolean("logged_in", false);
        		editor.commit();
          		toast("Logged Out");
          		setPrefs(false);
      		}
  		}
  	};	    
    
	private void restore_settings()
	{
        settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        editor = settings.edit();        
	}  
    
	//Toast Messages    
    private void toast(String msg)
    {
    	Context context = getApplicationContext();
    	Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();    	
    }		
}
